package com.tanxiaoyao.wecon.net;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

import com.tanxiaoyao.wecon.R;
import com.tanxiaoyao.wecon.common.UIHelper;
import com.tanxiaoyao.wecon.ui.ActivityHome;

import android.R.integer;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

/**
 * 全局连接类
 * 
 * @author tanxiaoyao(junlidev@gmail.com)
 *
 */
public class GlobalConnectHelper {
	// DEBUG标志
	private static final String TAG = "tanxiaoyao-globalconnector";
	private static final Boolean ISDEBUG = true;

	// 定义确定消息状态的常量
	public static final int MESSAGE_STATE_CHANGE = 1; // 传送过来的消息是表示当前改变后的状态标识
	public static final int MESSAGE_READ = 2; // 表示传过来的是要读取的信息
	public static final int MESSAGE_WRITE = 3; // 表示传过来的是要写入输出流的信息
	public static final int MESSAGE_DEVICE_NAME = 4; // 传送的是设备信息
	public static final int MESSAGE_TOAST = 5; // 传送的是要显示的提示TOAST

	public static GlobalConnectHelper globalConnector;
	
	public static boolean canSend = true;

	// 蓝牙适配器
	public static BluetoothAdapter btAdapter;
	// UUID码
	public static final String UUID = "00001101-0000-1000-8000-00805F9B34FB";
	// 蓝牙socket连接
	public static BluetoothSocket btSocket;
	// 蓝牙信息存储
	public static HashMap<String, String> blutooDevs;
	// 选中的蓝牙序号
	public static int checkedIndex;

	// 蓝牙连接服务
	private static BluetoothConnectService bluetoothConnectService;

	// 页面Handler集合
	private static List<Handler> handlerList = new LinkedList<Handler>();

	// 构造方法
	public GlobalConnectHelper() {

	}

	/**
	 * 注册本界面Handler到消息接受集合
	 * 
	 * @param handler
	 */
	public void addHandler(Handler handler) {
		handlerList.add(handler);
		if(ISDEBUG) Log.d(TAG, "添加界面" + handlerList.size());
	}

	/**
	 * 移除本界面的消息接收
	 * 
	 * @param handler
	 *            要移除的界面handler
	 * @return 1/0 移除成功/失败（可能是集合中没有这个handler）
	 */
	public boolean removehandler(Handler handler) {
		if (handlerList.contains(handler)) {
			handlerList.remove(handler);
			return true;
		}
		return false;
	}

	/**
	 * 发送消息到所有可接收界面
	 * 
	 * @param state
	 *            发送消息类别
	 * @param stateMsg
	 *            要发送的状态消息
	 */
	public void sendMsgToActivity(int state, int arg1, int arg2, String stateMsg) {
		if (!handlerList.isEmpty()) {
			// 循环所有handler并发送消息
			for (Handler h : handlerList) {
				h.obtainMessage(state, arg1, arg2, stateMsg).sendToTarget();
			}
			if(ISDEBUG) Log.d(TAG, "更新界面： " + stateMsg);
		}
	}

	// get
	public static GlobalConnectHelper getGlobalConnector() {
		if (globalConnector == null) {
			// 全局只允许有一个globalConnector，使用单例模式
			globalConnector = new GlobalConnectHelper();
		}
		return globalConnector;
	}

	/**
	 * 判断是否存在连接服务
	 * 
	 * @return 1/0：存在/不存在
	 */
	public boolean hasService() {
		if (ISDEBUG)
			Log.d(TAG, "hasService: " + (bluetoothConnectService != null));

		return (bluetoothConnectService != null);
	}

	/**
	 * 取得连接服务状态
	 * 
	 * @return 状态标识码
	 */
	public int getServiceState() {
		if (ISDEBUG)
			Log.d(TAG, "getServiceState: " + bluetoothConnectService.getState());
		return bluetoothConnectService.getState();
	}

	// 实现连接
	public void sendMess(String sendMsg) {
		// 这里先用打印log实现
		if (ISDEBUG)
			Log.d(TAG, sendMsg);
		if (bluetoothConnectService.getState() != BluetoothConnectService.STATE_CONNECTED) {
			if (ISDEBUG)
				Log.d(TAG, "state not connected,can not write");
			return;
		}
		if (sendMsg.length() > 0 && canSend) {
			// 格式化
			sendMsg += "\n";
			// 转换成字节流并发送
			byte[] send = sendMsg.getBytes();
			bluetoothConnectService.write(send);
			if (ISDEBUG)
				Log.d(TAG, "send:" + send);
			// bluetoothConnectService.getState();
		}
	}

	//接收信息使用handler传递
	public void reciveMess(String reciveMsg) {
		//去除回车符
		reciveMsg = reciveMsg.substring(0,reciveMsg.length() - 2);
		switch (reciveMsg) {
		case "is_setting":
			canSend = false;
			break;
		case "setting_over":
			canSend = true;
			break;
		default:
			break;
		}
		//发送接收到的信息给UI
		sendMsgToActivity(MESSAGE_READ,-1,-1,reciveMsg);
	}

	// ///////////////////////////////////////////////////
	//
	// 下面写一些初始化及建立连接的方法
	//
	// //////////////////////////////////////////////////

	/**
	 * 建立蓝牙连接对象
	 */
	public void creatConnectService() {
		if (bluetoothConnectService == null)
			bluetoothConnectService = new BluetoothConnectService();
		if (ISDEBUG)
			Log.d(TAG, "service created!");
	}

	/**
	 * 连接外部蓝牙设备
	 * 
	 * @param address
	 *            外部蓝牙设备地址
	 */
	public void connectDevice(BluetoothAdapter bleAdapter, String address) {
		// 取消蓝牙的可见性
		bleAdapter.cancelDiscovery();
		// 实例化远程设备
		BluetoothDevice device = bleAdapter.getRemoteDevice(address);
		// 开始连接设备
		bluetoothConnectService.connect(device);
		if (ISDEBUG)
			Log.d(TAG, "service connect!");
	}

	/**
	 * 开启连接服务
	 */
	public void startService() {
		bluetoothConnectService.start();
		if (ISDEBUG)
			Log.d(TAG, "service start!");
	}

}
